import { createStore } from 'vuex'
//在vuex初始化时导入插件
import persist from 'vuex-persistedstate'
export default createStore({
  state: {
    goodsList: [], // 购物车里面商品数据
  },
  getters: {
    cartNum(state){ // 购物车总数
      return state.goodsList.reduce((prev,now) => prev+now.buyNum,0);
    }
  },
  mutations: { // 固话插件监听的是mutations调用，如果不调用mutations方法去改变 state 里面的数据，不会触发存储。
    savaList(state,val){ // 保存购物车数据的方法
      let index = state.goodsList.findIndex(item => item.checkid == val.checkid);
      if (index>-1){
        state.goodsList[index].buyNum += val.buyNum;
      } else {
        state.goodsList.push(val);
      }
    },
    checkAll(state,bool){ // 全选的函数
      state.goodsList.forEach(item => {
        item.ischeck = bool;
      })
    },
    del(state,i){
      state.goodsList.splice(i,1);
    },
    delect(state){ // 删除的逻辑
      state.goodsList = state.goodsList.filter(item => !item.ischeck);
    },
    kong(){ }// 实现数据的保存
  },
  actions: {
  },
  modules: {
  },
  plugins: [
    new persist({
      storage: window.localStorage,
    }),
  ],
})
